<template>
	<view>
		<view class="edgeInsetTop"></view>
		<view class="wanl-order">
			<view class="address cu-list bg-white menu-avatar margin-bj radius-bock">
				<!-- <view class="tab-label-box ">
					<view :class="['item-tab', tabIndex == index ? 'item-tab-active' : '' ]" v-for="(item,index) in tabArr" :key="item.id" @click="tabIndex = index">{{ item.name }}</view>
				</view> -->
				<!-- 快速配送 -->
				<!-- 		<view class="cu-item" v-if="tabIndex == 0">
					<view class="cu-avatar round wanl-bg-orange"><text class="wlIcon-weizhi1"></text></view>
					<view class="content" v-if="addressData.address" @tap="userAddress()">
						<view>
							<text class="wanl-pip margin-right-sm">{{ addressData.name }}</text>
							<text class="wanl-gray-light text-sm">{{ addressData.mobile }}</text>
						</view>
						<view class="text-sm wanl-pip text-cut">{{ addressData.province}} {{ addressData.city }} {{ addressData.district }} {{ addressData.address }}</view>
					</view>
					<view class="content" @tap="addAddress('newadd')" v-else><view class="text-sm wanl-pip text-cut">点击此处填写收货地址</view></view>
					<view class="action"><text class="wlIcon-fanhui2 text-lg"></text></view>
				</view> -->

				<!-- 到店自提 -->
				<!-- <view class="cu-item-map">
					<view class="empty-map" @click="switchShopAddres" v-if="!userShop">
						<view class="empty-name">请选择自提点</view>
						<view class="action"><text class="wlIcon-fanhui2 text-lg"></text></view>
					</view>

					<view class="address-user-data" v-if="userShop">
						<view class="top-address text-orange border-bottom">
							<view class="address-name">自提点：<text>{{ userShop.city }}（{{ userShop.shopname }}）</text>
							</view>
							<image @click="switchShopAddres" class="select-icon-img"
								src="/static/images/shop/switch.png" mode=""></image>
						</view>
						<view class="two-address-detail">
							地址：{{ userShop.city + userShop.address}}
						</view>
						<view class="two-md-phone" @click="markPhone(userShop.sendPhoneNum)">
							<view class="md-phone text-gray">门店电话： <text>{{ userShop.sendPhoneNum }}</text></view>
							<image class="phone-icon-img" src="/static/images/shop/m7.png" mode=""></image>
						</view>
					</view>

				</view> -->
			</view>
			<view v-for="(shop, index) in orderData.lists" :key="index" class="lists bg-white margin-bj radius-bock">
				<view class="shopname">
					<text class="wanl-pip text-bold">商品信息</text>
				</view>
				<view class="cu-list menu-avatar">
					<view class="cu-item margin-bottom" v-for="(goods, key) in shop.products" :key="key">
						<view class="cu-avatar radius-bock"
							:style="{ backgroundImage: 'url(' + $wanlshop.oss(goods.image, 77, 77) + ')' }"></view>
						<view class="content">
							<view class="text-sm text-cut-2">{{ goods.title }}</view>
							<view class="wanl_sku text-sm">规格：<text v-for="(item, skey) in goods.sku.difference"
									:key="skey">
									<block v-if="skey != 0">-</block>{{ item }}
								</text>
							</view>
							<!-- <view class="text-sm text-sm margin-top-sm" style="color: #A1A1A1;">
								金额：<text class="text-decoration">{{goods.sku.market_price}}</text>
							</view> -->
						</view>
						<view class="action">
							<view class="wanl-pip text-sm flex align-center justify-end">
								<view class="text-orange">{{ goods.sku.price }}积分</view>
							</view>
							<view class="wanl-gray-light text-sm">x{{ goods.number }}</view>
						</view>
					</view>
				</view>
				<form>
					<view class="cu-form-group align-start border-bottom">
						<view class="wanl-gray-light title">备注</view>
						<textarea maxlength="-1" v-model="shop.remarks" placeholder="订单备注可选"></textarea>
					</view>
				</form>
				<view class="text-right margin-bj text-sm flex align-center justify-end">
					<text class="wanl-gray">共{{ shop.number }}件，</text>
					小计：
					<view class="text-orange">
						<text>{{ shop.order_price }}积分</text>
					</view>
				</view>
			</view>

			<view class="margin-bj">
				<view class="">
					<view>
						1、如果您购买的商品有任何问题，请直接与购买的门店联系！门店将为您处理，让您售后无忧！
					</view>
					<view class="margin-top-lg">
						2、如果您找不到购物的提货门店，请致电我们官方热线！<br />
						<text class="text-orange" @click="markPhone('18837589743')">18837589743</text>
						<image class="phone-icon-img" src="/static/images/shop/m7.png" mode=""></image>
					</view>
				</view>
			</view>

			<!-- 选择自提点 输入提货人姓名和手机号 -->
			<view class="lists bg-white margin-bj radius-bock" style="padding: 20rpx 25rpx;" v-if="tabIndex==1">
				<view class="cu-form-group align-center">
					<view class="wanl-gray-light title" style="margin-top:0rpx;">提货人姓名：</view>
					<input v-model="pick_name" placeholder="请输入提货人姓名"></input>
				</view>
				<view class="cu-form-group align-center">
					<view class="wanl-gray-light title" style="margin-top:0rpx;">提货人手机号：</view>
					<input type="number" v-model="pick_mobile" placeholder="请输入提货人手机号"></input>
				</view>
			</view>

			<view class="safeAreaBottom"> </view>
			<view class="wanlian cu-bar tabbar solid-top foot text-df">
				<view class="flex align-center justify-end">
					<text class="wanl-gray">共{{ orderData.statis.allnum }}件，</text>
					合计：
					<!-- 好人值 -->
					<view class="text-orange">
						<text>{{ orderPrice }}积分</text>
					</view>
				</view>
				<button @tap="addOrder" class="cu-btn round lg bg-gradual-orange margin-lr-bj">提交订单</button>
			</view>

			<!-- 弹出层 -->
			<view class="WANL-MODAL text-sm" @touchmove.stop.prevent="moveHandle">
				<!-- 优惠券 -->
				<view class="cu-modal bottom-modal" :class="modalName == 'coupon' ? 'show' : ''" @tap="hideModal">
					<view class="cu-dialog bg-bgcolor" @tap.stop="">
						<view class="wanl-modal">
							<view class="head padding-bj">
								<view class="content">
									<view class="text-lg">优惠券</view>
								</view>
								<view class="close wlIcon-31guanbi" @tap="hideModal"></view>
							</view>
							<scroll-view class="wanl-coupon scroll-y" scroll-y="true" v-if="couponIndex != null">
								<view v-for="(coupon, index) in orderData.lists[couponIndex].coupon" :key="index"
									:class="coupon.type" class="item margin-bottom-bj radius-bock">
									<image :src="$wanlshop.appstc('/coupon/bg_coupon_3x.png')" class="coupon-bg">
									</image>
									<image :src="$wanlshop.appstc('/coupon/img_couponcentre_received_3x.png')"
										class="coupon-sign" v-if="coupon.state"></image>
									<view class="item-left">
										<block
											v-if="coupon.type == 'reduction' || (coupon.type == 'vip' && coupon.usertype == 'reduction')">
											<view class="colour">
												<text class="text-price"></text>
												<text class="prices">{{Number(coupon.price)}}</text>
											</view>
											<view class="cu-tag wanl-gray-dark radius text-sm bg-white">
												满{{Number(coupon.limit)}}减{{Number(coupon.price)}}
											</view>
										</block>
										<block
											v-if="coupon.type == 'discount' || (coupon.type == 'vip' && coupon.usertype == 'discount')">
											<view class="colour">
												<text class="prices">{{Number(coupon.discount)}}</text>
												<text class="discount">折</text>
											</view>
											<view class="cu-tag wanl-gray-dark radius text-sm bg-white">
												满{{Number(coupon.limit)}}打{{Number(coupon.discount)}}折
											</view>
										</block>
										<block v-if="coupon.type == 'shipping'">
											<view class="colour">
												<text class="prices">包邮</text>
											</view>
											<view class="cu-tag wanl-gray-dark radius text-sm bg-white">
												满{{Number(coupon.limit)}}元包邮
											</view>
										</block>
									</view>
									<view class="item-right padding-bj">
										<view class="title">
											<view class="cu-tag sm radius margin-right-xs tagstyle">
												{{coupon.type_text}}
											</view>
											<text class="text-cut wanl-gray text-min">{{coupon.name}}</text>
										</view>
										<view class="content text-min">
											<view class="wanl-gray">

												<view v-if="coupon.grant != '-1'">
													<text class="wlIcon-dot"></text>目前仅剩余 {{coupon.surplus}} 张
												</view>

												<view v-if="coupon.drawlimit != 0">
													<text class="wlIcon-dot"></text>每人仅限领取 {{coupon.drawlimit}} 张
												</view>
												<block v-if="coupon.pretype == 'fixed'">
													<view>
														<text class="wlIcon-dot"></text>生效 {{coupon.startdate}}
													</view>
													<view>
														<text class="wlIcon-dot"></text>结束 {{coupon.enddate}}
													</view>
												</block>
												<block v-if="coupon.pretype == 'appoint'">
													<view v-if="coupon.validity == 0">
														<text class="wlIcon-dot"></text>未使用前 永久 有效
													</view>
													<view v-else>
														<text class="wlIcon-dot"></text>领取后 {{coupon.validity}} 天有效
													</view>
												</block>
											</view>
											<view class="cu-btn sm round line-colour" @tap="onCoupons(index)"
												v-if="coupon.state">
												<text v-if="coupon.choice"> 已选择 </text>
												<text v-else> 立即使用 </text>
											</view>
											<view class="cu-btn sm round" @tap="onReceive(index)" v-else>
												立即领取
											</view>
										</view>
									</view>
								</view>
							</scroll-view>
							<view class="foot padding-lr-bj"><button
									class="cu-btn bg-gradual-orange round text-bold complete"
									@tap="hideModal">完成</button></view>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				optionData: {},
				addressData: {},
				modalName: null, // 弹出层
				cartType: null,
				couponData: {},
				couponIndex: null,
				radioType: false,
				isHaorenShop: 0, //0 好人值+金额支付  1纯金额支付  2传好人值支付
				userShop_id: 0, //用户选择的自提店id
				userShop: null, //用户选择的自提点
				tabArr: [{
					id: 1,
					name: '快速配送'
				}, {
					id: 2,
					name: '到店自提'
				}],
				tabIndex: 0,
				orderData: {
					lists: [],
					statis: {
						allnum: 1,
						allsub: 0
					}
				},
				pick_mobile: '',
				pick_name: '',
				priceData: {
					price: '',
					marketPrice: ''
				},
				orderPrice: '',
			};
		},
		onLoad(option) {

			if (option.isHaoren)
				if (option.isHaoren) this.isHaorenShop = Number(option.isHaoren)
			this.optionData = JSON.parse(option.data);
			this.loadData();
			this.cartType = option.type;
			//判断用户是否绑定店铺
			if (this.user.shop_id) this.getUserShopDetail(this.user.shop_id);
			let {
				shop_id
			} = this.user;
			if (shop_id != 0) this.userShop_id = shop_id;
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			userShop_id(newValue) {
				this.getUserShopDetail(newValue);
			},
			// 是否使用好人值抵消
			radioType(val) {
				// if(val) {
				// 	// 用户当前的好人值 < 当前支付价格 ？ 当前价格 - 好人值
				// 	// 用户当前的好人值 == 当前支付价格 ? 0.01
				// 	// 用户当前的好人值 > 当前支付价格 ? 0.01
				// 	let { user:{ haoren_number }, orderData:{ statis: { allsub }}} = this;
				// 	let price
				// 	if(haoren_number < allsub) price = this.$wanlshop.bcsub(allsub,haoren_number);
				// 	if(haoren_number == allsub || haoren_number > allsub) price = 0.01

				// 	price = price || 0.01
				// 	this.orderData.statis.allsub = price
				// }
			}
		},
		methods: {
			async loadData(address_id) {
				this.$api.post({
					url: '/wanlshop/order/getOrderGoodsList',
					loadingTip: '加载中',
					data: {
						data: this.optionData,
						address_id: address_id
					},
					success: res => {
						this.orderData = res.orderData;
						this.priceData.price = res.orderData.lists[0].products[0].sku.price;
						this.priceData.marketPrice = res.orderData.lists[0].products[0].sku.market_price;
						res.orderData.lists.forEach((item) => {
							this.orderPrice += item.order_price
						});
						if (res.addressData) {
							this.addressData = res.addressData;
						} else {
							// this.addAddress('newadd');
						}
					}
				});
			},
			// 获取自提点信息
			getUserShopDetail(id) {
				// 获取店铺详情
				let self = this;
				this.$api.post({
					url: '/wanlshop.shop/offlineShop',
					data: {
						id: this.$store.state.user.shop_id
					},
					success(res) {
						self.userShop = res
					}
				})
			},

			//切换自营店
			switchShopAddres() {
				uni.navigateTo({
					url: "/pages/user/selfshop?order=1"
				})
			},

			//拨打电话
			markPhone(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				})
			},

			// 提交订单
			async addOrder() {
				if (this.orderData.statis.allnum === 0) {
					this.$wanlshop.msg('订单异常')
					return;
				}
				let address_id = this.addressData.id;
				if (address_id === 0) {
					this.$wanlshop.msg('请填写地址')
					return;
				}
				if (this.tabIndex == 1 && this.pick_name == '') {
					uni.showToast({
						title: '提货人姓名不能为空',
						icon: 'none',
						duration: 1000
					})
					return;
				}
				if (this.tabIndex == 1 && this.pick_mobile == '') {
					uni.showToast({
						title: '提货人电话不能为空',
						icon: 'none',
						duration: 1000
					})
					return;
				}
				let data = {
						lists: [],
						// address_id: address_id
						address_id: this.$store.state.user.shop_id
					},
					cart = [];
				// type 1快递  2自提
				data.type = this.tabArr[1].id;
				data.to_shop_id = data.type == 2 ? this.userShop_id : 0
				data.pick_mobile = this.pick_mobile
				data.pick_name = this.pick_name
				this.orderData.lists.forEach((item, index) => {
					data.lists.push({
						shop_id: item.shop_id,
						remarks: item.remarks,
						products: [],
						//店铺优惠券和其他 在下追加
						coupon_id: this.couponData[index] ? this.couponData[index].id : 0
					});
					item.products.forEach(goods => {
						// 购物车数据
						cart.push({
							goods_id: goods.id,
							sku_id: goods.sku.id
						});
						// 商品数据
						data.lists[index].products.push({
							goods_id: goods.id,
							number: goods.number,
							sku_id: goods.sku.id,
							freight_id: goods.freight_id
						});
					});
				});
				// 提交订单数据data
				this.$api.post({
					url: '/wanlshop/order/addOrder',
					data: {
						order: data,
						is_haoren: this.radioType ? 1 : 0
					},
					loadingTip: '提交订单中...',
					success: res => {
						this.$store.commit('statistics/order', {
							pay: this.$store.state.statistics.order.pay + cart.length
						});
						// 如果使用优惠券全局减去
						let coupon = Object.keys(this.couponData).length;
						if (coupon != 0) {
							this.$store.commit('statistics/dynamic', {
								coupon: this.$store.state.statistics.dynamic.coupon - coupon
							});
						}
						// 大厂软件，就是这么迷幻
						if (this.cartType == 'cart') {
							this.$store.dispatch('cart/del');
						}
						let isHaoren = this.isHaorenShop; // 带过去支付类型
						this.$wanlshop.to(
							`/pages/shop/money/pay?data=${JSON.stringify(res)}&isHaoren=${isHaoren}&priceData=${JSON.stringify(this.priceData)}`
						);
					}
				});
			},
			//添加或修改成功之后回调
			async refreshList(data, type) {
				this.$api.post({
					url: '/wanlshop/address/address',
					data: {
						data: data,
						type: 'add'
					},
					success: res => {
						this.addressData = res;
					}
				});
			},
			// 查询优惠券，减缓服务器压力，单独查询（仅查询首次）
			async queryCoupon(index) {
				let data = this.orderData.lists[index];
				if (data.coupon.length == 0) {
					let goods_id = [];
					let shop_category_id = [];
					for (var i = 0; i < data.products.length; i++) {
						goods_id.push(data.products[i]['id']);
						shop_category_id.push(data.products[i]['shop_category_id']);
					};
					this.$api.post({
						url: '/wanlshop/coupon/query',
						data: {
							shop_id: data.shop_id,
							goods_id: this.unique(goods_id),
							shop_category_id: this.unique(shop_category_id),
							price: data.order_price
						},
						success: res => {
							data.coupon = res;
						}
					});
				}
				this.couponIndex = index;
				this.modalName = 'coupon';
			},
			// 领取优惠券
			async onReceive(index) {
				let coupon = this.orderData.lists[this.couponIndex].coupon[index];
				this.$api.post({
					url: '/wanlshop/coupon/receive',
					loadingTip: '领取中',
					data: {
						id: coupon.id
					},
					success: res => {
						coupon.id = res.id;
						coupon.state = true;
						this.$wanlshop.msg(res.msg);
						this.$store.commit('statistics/dynamic', {
							coupon: this.$store.state.statistics.dynamic.coupon + 1
						});
					}
				});
			},
			// 选中优惠券, 将优惠券放进数组中
			onCoupons(index) {
				let order = this.orderData.lists[this.couponIndex];
				let data = this.orderData.lists[this.couponIndex].coupon;
				data[index].choice = !data[index].choice;
				if (data[index].choice) {
					// 遍历取消掉其他选择的状态，for性能高于其他历遍
					for (var i = 0; i < data.length; i++) {
						if (i != index) {
							data[i].choice = false;
						}
					};
					// 更新选择
					this.couponData[this.couponIndex] = data[index];
					// @ 精度计算 this.$wanlshop.bcadd('0.132123',0.132123)
					// 满减计算
					if (data[index].type == 'reduction' || (data[index].type == 'vip' && data[index].usertype ==
							'reduction')) {
						order.freight.price = order.freight_price_bak;
						order.sub_price = this.$wanlshop.bcsub(this.$wanlshop.bcadd(order.order_price, order.freight
							.price), data[index].price);
						if (order.sub_price < 0) {
							order.sub_price = 0.01;
						}
					}
					// 折扣计算  前端出问题
					if (data[index].type == 'discount' || (data[index].type == 'vip' && data[index].usertype ==
							'discount')) {
						let discount = data[index].discount > 10 ? this.$wanlshop.bcdiv(data[index].discount, 100) : this
							.$wanlshop.bcdiv(data[index].discount, 10);
						order.freight.price = order.freight_price_bak;
						order.sub_price = this.$wanlshop.bcadd(this.$wanlshop.bcmul(order.order_price, discount), order
							.freight.price);
					}
					// 包邮计算
					if (data[index].type == 'shipping') {
						order.freight.price = 0;
						order.sub_price = order.order_price;
					}
				} else {
					// 恢复原价 1.0.2升级
					this.couponData = {};
					if (data[index].type == 'shipping') {
						order.freight.price = order.freight_price_bak;
					}
					order.sub_price = this.$wanlshop.bcadd(order.order_price, order.freight.price);
				}
				// 精度计算合计
				this.orderData.statis.allsub = 0;
				for (var i = 0; i < this.orderData.lists.length; i++) {
					this.orderData.statis.allsub = this.$wanlshop.bcadd(this.orderData.statis.allsub, this.orderData.lists[
						i].sub_price);
				};
				this.modalName = null;
			},
			// 修改数量
			changeNum(num) {
				num = num == 0 ? 1 : num;
				this.orderData.lists[0].number = num;
				this.orderData.lists[0].products[0].number = num;
				this.orderData.statis.allnum = num;
				// 计算价格
				this.orderData.lists[0].sub_price = this.$wanlshop.bcmul(this.orderData.lists[0].products[0].sku.price,
					num);
				this.orderData.statis.allsub = this.$wanlshop.bcmul(this.orderData.lists[0].products[0].sku.price, num);
			},
			addAddress(type) {
				this.$wanlshop.to(`/pages/user/address/addressManage?type=${type}`);
			},
			userAddress() {
				this.$wanlshop.to('/pages/user/address/address?source=1');
			},
			// 弹出层，暂时不需要但后续版本可能需要
			showModal(name) {
				this.modalName = name;
			},
			// 关闭弹出层
			hideModal() {
				this.modalName = null;
			},
			// 数组去重并字符串
			unique(arr) {
				return Array.from(new Set(arr)).join(',');
			},
			//禁止父元素滑动
			moveHandle() {}
		}
	};
</script>

<style scoped>
	.border-bottom {
		border-bottom: 2rpx solid #EEEEEE;
	}

	.text-decoration {
		text-decoration: line-through;
		text-decoration-color: #A1A1A1;
	}

	.tab-label-box {
		display: flex;
		border-bottom: solid 4rpx #fe6500;
	}

	.tab-label-box .item-tab {
		flex: 1;
		width: 100;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 35rpx;
		font-weight: bold;
		height: 80rpx;
	}

	.tab-label-box .item-tab-active {
		background: #fe6500;
		color: white;
		border-radius: 18rpx 18rpx 0 0;
	}

	.cu-item-map {
		padding: 30rpx 23rpx 35rpx;
		box-sizing: border-box;
	}

	.empty-map {
		height: 140rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.empty-map .empty-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #ff0000;
	}

	.address-user-data {
		display: flex;
		flex-direction: column;
	}

	.top-address {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 25rpx;
	}

	.address-name {
		font-size: 33rpx;
		font-weight: 800;
		color: #ff0404;
		margin-bottom: 6rpx;
	}

	.select-icon-img {
		width: 43rpx;
		height: 43rpx;
	}

	.two-address-detail {
		font-size: 28rpx;
		color: #949494;
		line-height: 40rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.two-md-phone {
		display: flex;
		align-items: center;
	}

	.md-phone {
		font-size: 30rpx;
		/* color: #da5600; */
		font-weight: 500;
		margin-right: 10rpx;
	}

	.phone-icon-img {
		width: 30rpx;
		height: 30rpx;
	}

	.label-icon-money {
		width: 34rpx;
		height: 34rpx;
		margin-right: 15rpx;
	}

	.label-icon-money image {
		width: 100%;
		height: 100%;
	}

	.label-desc {
		font-size: 26rpx;
		font-weight: 500;
	}
</style>
